package com.sh.gateway.service;

import com.sh.gateway.common.JsonMapper;
import com.sh.gateway.entity.PermissionMenu;
import com.sh.gateway.entity.Role;
import com.sh.gateway.entity.User;
import com.sh.gateway.mapper.IPermissionMenuMapper;
import com.sh.gateway.mapper.IRoleMapper;
import com.sh.gateway.mapper.IUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: he changjie on 2019/2/10
 * @Description:
 */
@Service
public class RoleService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private IRoleMapper roleMapper;
    @Autowired
    private IUserMapper userMapper;
    @Autowired
    private PermissionMenuServcie menuServcie;
    @Autowired
    private IPermissionMenuMapper menuMapper;

    /**
     * 添加一名角色
     * @param role 角色
     * @return
     */
    public int add(Role role){
        if(StringUtils.isEmpty(role.getRoleName())){
            return -1;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = dateFormat.format(new Date());
        role.setCreateTime(createTime);
        role.setRoleId(String.valueOf(System.currentTimeMillis()));
        if(StringUtils.isNotEmpty(role.getMenuId())){
            String[] split = role.getMenuId().split(",");
            if(split.length>0){
                for (Object o : split) {
                    String temp=String.valueOf(o);
                    role.setMenuId(menuServcie.queryIdByName(temp));
                    roleMapper.insertSelective(role);
                }
            }
            return 1;
        }else{
            return roleMapper.insertSelective(role);
        }
    }


    /**
     * 更新一名角色的名称或权限
     * 该角色有集合中的权限则略过，无则添加，多则删除
     * @param id 角色ID
     * @param name 名称
     * @param menus 权限菜单集合（以,间隔）
     * @return
     */
    public int update(String id,String name,String menus){
        if(StringUtils.isEmpty(id)){
            return -1;
        }
        Example example = new Example(Role.class);
        example.setDistinct(true);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("roleId",id);
        criteria.andIsNull("flag");

        //拉取该用户当前的权限
        Role roleState = this.queryOne(id);
        if(StringUtils.isNotEmpty(menus) && StringUtils.isNotEmpty(name)){
            roleState.setRoleName(name);
            roleMapper.deleteByExample(example);
            //更新权限
            String[] split = menus.split("[,，]");
            if(split.length>0){
                for (String s : split) {
                    roleState.setMenuId(menuServcie.queryIdByName(s));
                    roleMapper.insertSelective(roleState);
                }
            }else{
                roleState.setMenuId(null);
                roleMapper.insertSelective(roleState);
            }
            return 1;
        }else if(StringUtils.isNotEmpty(name)){
            Role roleT=new Role();
            roleT.setRoleId(id);
            roleT.setRoleName(name);
            roleT.setCreateTime(roleState.getCreateTime());
            roleMapper.deleteByExample(example);
            roleMapper.insertSelective(roleT);
            return 1;
        }
        return -1;
    }

    /**
     * 删除一名角色
     * 级联将为该角色的用户的角色至为null;
     * @param id
     * @return
     */
    public int delete(String id){
        //级联
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("roleId",id);
        List<User> userList = userMapper.selectByExample(example);
        if(userList!=null && userList.size()>0){
            for (User user : userList) {
                user.setRoleId(null);
                userMapper.updateByPrimaryKey(user);
            }
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String deleteTime = dateFormat.format(new Date());
        Role role = new Role();
        role.setFlag("-1");
        role.setDeleteTime(deleteTime);
        Example example1 = new Example(Role.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("roleId",id);
        return roleMapper.updateByExampleSelective(role,example1);
    }


    /**
     * 通过主键查询角色
     * @param id ID
     * @return
     */
    public Role queryOne(String id){
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("roleId",id);
        List<Role> roles = roleMapper.selectByExample(example);
        return roles!=null&&roles.size()>0?roles.get(0):null;
    }

    /**
     * 分页
     * 拉取所有角色信息列表
     * @return
     */
    public List<Object> queryAll(String search,int currentPage,int pageSize){
        List<Object> result=new ArrayList<>();
        List<Object> result2=new ArrayList<>();
        RowBounds rowBunds = new RowBounds((currentPage - 1) * pageSize, pageSize);
        Example example = new Example(Role.class);
        example.setOrderByClause("role_name asc");
        Example.Criteria criteria = example.createCriteria();
        criteria.andIsNull("flag");
        if(StringUtils.isNotEmpty(search)){
            criteria.andLike("roleName","%"+search+"%");
        }
        List<Role> roles = roleMapper.selectByExampleAndRowBounds(example,rowBunds);
        if(roles!=null && roles.size()>0){
            for (Role role : roles) {
                if(!result.contains(role.getRoleId())){
                    result.add(role.getRoleId());
                    List<PermissionMenu> menus = this.queryAllByRoleId(role.getRoleId());
                    if(menus!=null && menus.size()>0){
                        StringBuilder menuT= new StringBuilder();
                        for (PermissionMenu menu : menus) {
                            if(menu!=null){
                                menuT.append(menu.getMenuName()).append(",");
                                role.setMenuId(menuT.toString().substring(0,menuT.lastIndexOf(",")));
                            }
                        }
                    }
                    result2.add(role);
                }
            }
            return result2;
        }
        return null;
    }
    /**
     * 拉取所有角色数量
     * @return
     */
    public int queryAll(String search){
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIsNull("flag");
        if(StringUtils.isNotEmpty(search)){
            criteria.andLike("roleName","%"+search+"%");
        }
        List<Role> roles = roleMapper.selectByExample(example);
        if(roles!=null && roles.size()>0){
            List<Object> result=new ArrayList<>();
            for (Role role : roles) {
                if(!result.contains(role.getRoleId())){
                    result.add(role.getRoleId());
                }
            }
            return result.size();
        }else{
            return 0;
        }
    }

    /**
     * 通过角色ID查询所属权限列表
     * @param id
     * @return
     */
    public List<PermissionMenu> queryAllByRoleId(String id){
        if(StringUtils.isEmpty(id)){
            return null;
        }
        List<PermissionMenu> result=new ArrayList<>();
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("roleId",id);
        List<Role> roles = roleMapper.selectByExample(example);
        if(roles!=null && roles.size()>0){
            for (Role role : roles) {
                PermissionMenu menu = menuMapper.selectByPrimaryKey(role.getMenuId());
                if(menu!=null){
                    result.add(menu);
                }
            }
            return  result;
        }
        return null;
    }

}
